<script setup lang="ts">
import {getUserSecurityInfoApi,PasswordModle,UpdateUserPassWordApi,EmailModle,getEmailCode,bindEmailApi} from '~@/api/account'
import { notification,type FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form';
import { encryptByRSA } from '~@/utils/crypto'
import { getPublicKey } from '~@/api/auth'
import { ResponseCode } from '~@/api/response.code'


interface DataItem {
  key:string
  title: string
  desc: string
  value:string
}
const { t } = useI18n()
const updateKey = ref(0);
let data = computed<DataItem[]>(() => {
  return [
    {
      key:'isInitPassword',
      title: '账户密码',
      desc: '当前密码强度:',
      value: ''
    },
    {
      key:'phone',
      title: '手机',
      desc: '已绑定手机:',
      value: ''
    },
    {
      key:'email',
      title: '邮箱',
      desc: '已绑定邮箱:',
      value: ''

    },
  ]
})

let publicKey: string = ''  // 公钥
const passwordVisible = ref(false)
const formPasswordRef = ref<FormInstance>()
const passwordFormData = ref<PasswordModle>({
  newPwd: '',
  oldPwd: '',
  rePwd: ''
})

const rules: any = computed(() => {
  return {
    oldPwd: [
      { required: true, message: '请输入旧密码', trigger: 'blur' },
      { min: 6, message: '至少 6 个字符以上', trigger: 'blur' }
    ],
    newPwd: [
      { required: true, message: '请输入旧密码', trigger: 'blur' },
      { min: 6, message: '至少 6 个字符以上', trigger: 'blur' }
    ],
    rePwd: [
      { required: true, validator: validateRePwd, trigger: 'blur' },
      { min: 6, message: '至少 6 个字符以上', trigger: 'blur' }
    ],
  }
})

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

const validateRePwd = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入旧密码');
  }else if(value != passwordFormData.value.newPwd){
    return Promise.reject('新密码与确认密码不一致');
  } else {
    if (passwordFormData.value.rePwd !== '') {
      formPasswordRef.value?.validateFields('rePwd');
    }
    return Promise.resolve();
  }
};

onMounted(async () => {
  return await securityInfo();
})
// 基础信息
async function securityInfo() {
  let res: any;
  res = await getUserSecurityInfoApi();
  
  if(res.data){
    for(var i = 0;i < data.value.length;i++) {
      if(data.value[i].key == 'isInitPassword'){
        data.value[i].value = res.data.isInitPassword?'强':'弱';
      }
      if(data.value[i].key == 'phone'){
        data.value[i].value = res.data.phone?res.data.phone:'';
        data.value[i].desc = res.data.phone?'已绑定手机：':'未绑定手机：';
      }
      if(data.value[i].key == 'email'){
        data.value[i].value = res.data.email?res.data.email:'';
        data.value[i].desc = res.data.email?'已绑定邮箱：':'未绑定邮箱：';
      }
    }
    // 操作数据后更新视图
	  updateKey.value += 1;
    console.log(data.value);

    notification.success({message: '查询成功'});
  }else{
    notification.error({message: res.message??'查询失败'});
  }
}
async function handleEdit(key: string){
  if(key=='isInitPassword'){
    passwordVisible.value = true;
    loadPublicKey()
  }else if(key=='email'){
    emailVisible.value = true;
  }
}
// 修改
async function handlePasswordOk() {
  try {
    await formPasswordRef.value?.validate();
    let res: any;
    const params = {
      oldPwd:encryptByRSA(publicKey, passwordFormData.value.oldPwd || '') as string,
      newPwd:encryptByRSA(publicKey, passwordFormData.value.newPwd || '') as string
    }
    res = await UpdateUserPassWordApi(params);
    if(res.code==1000){
      notification.success({message: '保存成功'});     
      passwordVisible.value = false;
    }else{
      notification.error({message: res.message??'保存失败'});     
    }
  }catch (errorInfo) {
    console.log('失败:', errorInfo);
  }
}
async function loadPublicKey() {
    const res = await getPublicKey()
    if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data)
            publicKey = res.data
    }
}
function handleCancel() {
  // formPasswordRef.value?.resetFields()
  // passwordVisible.value = false;
}

const emailVisible = ref(false)
const emailFormData = ref<EmailModle>({
  email: '',
  code: ''
})
// const formEmailRef = ref<FormInstance>()
const formEmailRef = shallowRef()
const codeLoading = shallowRef(false)
const resetCounter = 60

const { counter, pause, reset, resume, isActive } = useInterval(1000, {
    controls: true,
    immediate: false,
    callback(count) {
        if (count) {
            if (count === resetCounter)
                pause()
        }
    },
})
async function getCode() {
  codeLoading.value = true
  try {
      await formEmailRef.value.validateFields(['mobile', 'captcha'])
      if (!emailFormData.value.email) {
        notification.error({message: '请先填写邮箱'});
        codeLoading.value = false
        return
      }
      const { code, message } = await getEmailCode(emailFormData.value.email)
      if (code === 1000) {
        reset()
        resume()
        notification.success({message: message||'验证码发送成功，请注意查收'});
      }
      else {
        notification.error({message: message||'发送失败，未知原因'});
      }
      codeLoading.value = false
  }
  catch (error) {
      // TODO
      codeLoading.value = false
  }
}

// 绑定
async function handleEmailOk() {
  try {
    await formEmailRef.value?.validate();
    let res: any;
    // const params = emailFormData.vlu
    res = await bindEmailApi(emailFormData.value);
    if(res.code==1000){
      notification.success({message: '保存成功'});     
      passwordVisible.value = false;
    }else{
      notification.error({message: res.message??'保存失败'});     
    }
  }catch (errorInfo) {
    console.log('失败:', errorInfo);
  }
}
</script>

<template>
    <a-card :title="t('account.settings.security-setting')" :bordered="false">
        <a-list item-layout="horizontal" :data-source="data" :key="updateKey">
            <template #renderItem="{ item }">
                <a-list-item>
                    <a-list-item-meta :description="item.desc + item.value">
                        <template #title>
                            {{ item.title }}
                        </template>
                    </a-list-item-meta>
                    <template #actions>
                        <a-button type="link"  @click="handleEdit(item.key as string)" v-if="item.key !='phone'">
                            修改
                        </a-button>
                    </template>
                </a-list-item>
            </template>
        </a-list>
    </a-card>
    <a-modal v-model:open="passwordVisible" title="修改密码" @ok="handlePasswordOk" @cancel="handleCancel" :maskClosable="false">
      <a-form ref="formPasswordRef" :rules="rules" :model="passwordFormData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item name="oldPwd" label="旧密码">
          <a-input v-model:value="passwordFormData.oldPwd" type="password" show-count :minlength="6" placeholder="请输入旧密码" />
        </a-form-item>
        <a-form-item name="newPwd" label="新密码">
          <a-input v-model:value="passwordFormData.newPwd" type="password" show-count :minlength="6" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item name="rePwd" label="确认密码">
          <a-input v-model:value="passwordFormData.rePwd" type="password" show-count :minlength="6" placeholder="请输入确认密码" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="emailVisible" title="绑定邮箱" @ok="handleEmailOk" @cancel="handleCancel" :maskClosable="false">
      <a-form ref="formEmailRef"  :model="emailFormData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item name="email" label="邮箱" :rules="[{ type: 'email' }]">
          <a-input v-model:value="emailFormData.email" show-count placeholder="请输入旧邮箱" 
          style="width: 60%; margin-right: 8px;"/>
          <a-button :loading="codeLoading" :disabled="isActive" type="primary" @click="getCode">
              <template v-if="!isActive">
                  {{ t('pages.login.phoneLogin.getVerificationCode') }}
              </template>
              <template v-else>
                  {{ resetCounter - counter }} {{ t('pages.getCaptchaSecondText') }}
              </template>
          </a-button>
        </a-form-item>
        <a-form-item name="code" label="验证码" :rules="[{ required: true }]">
          <a-input v-model:value="emailFormData.code" type="password" show-count placeholder="请输入验证码" />
        </a-form-item>
      </a-form>
    </a-modal>
</template>

<style scoped lang="less">
:deep(.ant-card-body) {
  padding-left: 0 !important;
}
</style>
